using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace ServerManager.Network
{
    public class DrachamNetwork
    {
        private TcpClient client;
        private IPAddress host;
        private Int32 port;
        private NetworkHandler networkHandler;

        public NetworkHandler NetworkHandler
        {
            get
            {
                return this.networkHandler;
            }
        }

        public DrachamNetwork(IPAddress host, Int32 port)
        {
            this.host = host;
            this.port = port;

            client = new TcpClient();
            client.Connect(new IPEndPoint(host, port));
            if (!client.Connected)
            {
                throw new Exception("Unable to connect to server!");
            }

            this.networkHandler = new NetworkHandler(client);
        }

        public void Invoke(MessageType rt, params NetworkParameter[] parameters)
        {
            NetworkParameter requestParameter = new NetworkParameter(((Int32)rt).ToString(), 2);

            this.client.Client.Send(requestParameter.GetParameter());
            foreach (NetworkParameter param in parameters)
            {
                this.client.Client.Send(param.GetParameter());
            }
        }

        public String ReceiveString(Int32 bytesLength)
        {
            Byte[] b = new Byte[bytesLength];
            this.client.Client.Receive(b, bytesLength, SocketFlags.None);

            return Encoding.UTF8.GetString(b).Replace("\x00", "");
        }

        public Int32 ReceiveInt32(Int32 bytesLength)
        {
            return Convert.ToInt32(ReceiveString(bytesLength));
        }
    }
}
